package com.guigu.common.request;

import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:HttpUrlUtils
 * @Description:使用第三方服务发送请求工具类
 * @Author:taoLong
 * @Date:2021/11/12:15:55 星期五
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */

public class HttpUrlUtils {

    /**
     * 通过okhttp发送一个请求,返回Map
     *
     * @param url 请求地址
     * @return
     */
    public static Map<String, Object> sendUrl(String url) {
        Map<String, Object> map = new HashMap<>();
        OkHttpClient okHttpClient = new OkHttpClient();
        /**
         * 使用okhttp发送url请求
         */
        Request request = new Request.Builder().get().url(url).build();
        Call call = okHttpClient.newCall(request);
        /**
         *使用异步调用,并设置回调函数
         */
        /*        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                throw new TmsException(ResultCode.ERROR_CODE, "远程调用失败,稍后在失败把!");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                map.put("message", response.message());
            }
        });*/
        Response execute = null;
        try {
            execute = call.execute();
            map.put("message", execute.body().string());
        } catch (IOException e) {
            e.printStackTrace();
            throw new TmsException(ResultCode.ERROR_CODE, "远程调用出异常了!");
        }

        return map;
    }
}
